package com.fivetalks.client;

import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.fivetalks.object.ChatMessage;
import com.fivetalks.object.RoomInfo;

public class ChatThread extends Thread {
	SocketClient sc;

	public ChatThread(SocketClient sc) {
		this.sc = sc;
	}

	public void run() {

		String line = null;
		try {
			while ((line = sc.getDis().readUTF()) != null) {
				if ("login".equals(line) && sc.chatLobbyActivity != null) {
					try {
						sc.chatLobbyActivity.roomList.clear();
						sc.chatLobbyActivity.refreshView();

						while (true) {

							sc.chatLobbyActivity.title = sc.getDis().readUTF();
							Log.d("lobby", "title: "
									+ sc.chatLobbyActivity.title);
							if ("--endRoomList--"
									.equals(sc.chatLobbyActivity.title)) {
								break;
							}
							RoomInfo room = new RoomInfo();
							room.setTitle(sc.chatLobbyActivity.title);

							room.setRoomNumber(Long.parseLong(sc.getDis()
									.readUTF()));
							sc.chatLobbyActivity.readyRoomNumber.add(room
									.getRoomNumber());
							room.setLimitCount(Integer.parseInt(sc.getDis()
									.readUTF()));
							room.setCurrMale(Integer.parseInt(sc.getDis()
									.readUTF()));
							Log.d(room.getCurrFemale() + "",
									room.getCurrFemale() + "");
							room.setCurrFemale(Integer.parseInt(sc.getDis()
									.readUTF()));
							room.setStatus(sc.getDis().readUTF());
							Log.d(room.getStatus(), "내가만든거");

							if (sc.chatLobbyActivity.isReady()) {
								if ("Ready".equals(room.getStatus()))
									sc.chatLobbyActivity.addResult(room);
							} else {
								sc.chatLobbyActivity.addResult(room);
							}
						}
						sc.getDos().flush();
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				} else if ("createRoom".equals(line)
						&& sc.roomDialogActivity != null) {
					try {
						while (true) {
							sc.roomDialogActivity.roomNumber = Long
									.parseLong(sc.getDis().readUTF());
							Log.d("test", "roomNumber: "
									+ sc.roomDialogActivity.roomNumber);
							if (-1 == sc.roomDialogActivity.roomNumber) {
								break;
							}
							sc.roomDialogActivity.roomNo = sc.roomDialogActivity.roomNumber;
							sc.roomDialogActivity.isThreadEnd = true;
						}
					} catch (Exception ex) {
						ex.printStackTrace();
					}

				} else if("enterReadyRoom".equals(line)
						&& sc.preChatActivity != null) {
					sc.preChatActivity.title = sc.getDis().readUTF();
					Log.d("prechat","Title:" + sc.preChatActivity.title);
					sc.preChatActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// 해당 작업을 처리함
							sc.preChatActivity.tvRoomTitle.setText(sc.preChatActivity.title);
			
						}
					});
					
				}
				
				
				else if ("refreshReadyRoom".equals(line)
						&& sc.preChatActivity != null) {

					try {
						int numMember = Integer.parseInt(sc.getDis().readUTF());
						Log.d("prechat", "numMember: " + numMember);
						sc.preChatActivity.leader = Long.parseLong(sc.getDis()
								.readUTF());
						Log.d("prechat", "leader: " + sc.preChatActivity.leader);

						if (sc.getUserId() == sc.preChatActivity.leader) {
							sc.preChatActivity.btStart.setClickable(true);
						} else {
							sc.preChatActivity.btStart.setClickable(false);
							sc.preChatActivity.btStart.setVisibility(View.INVISIBLE);
						}

						for (int i = 0; i < numMember; i++) {
							Long id = Long.parseLong(sc.getDis().readUTF());
							Log.d("prechat", "id: " + id);

							String gender = sc.getDis().readUTF();
							Log.d("prechat", "gender: " + gender);

							final String nickname = sc.getDis().readUTF();
							Log.d("prechat", "nickname :" + nickname);
							final int age = Integer.parseInt(sc.getDis()
									.readUTF());
							Log.d("prechat", "age :" + age);
							int position = Integer.parseInt(sc.getDis()
									.readUTF());
							Log.d("prechat", "position: " + position);
							Log.d("prechat", "tvUser" + position);
							sc.preChatActivity.ibUser = (ImageView) sc.preChatActivity
									.findViewById(sc.preChatActivity
											.getResources().getIdentifier(
													"ibUser" + position,
													"id",
													sc.preChatActivity
															.getPackageName()));
							sc.preChatActivity.tvUser = (TextView) sc.preChatActivity
									.findViewById(sc.preChatActivity
											.getResources().getIdentifier(
													"tvUser" + position,
													"id",
													sc.preChatActivity
															.getPackageName()));

							URL imageURL = new URL(
									"http://zeropol2.iptime.org:8080/myproject/resources/mask_"
											+ id + ".jpg");
							HttpURLConnection conn = (HttpURLConnection) imageURL
									.openConnection();
							BufferedInputStream bis = new BufferedInputStream(
									conn.getInputStream(), 10240);
							sc.preChatActivity.bm = BitmapFactory
									.decodeStream(bis);
							bis.close();

							sc.preChatActivity.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// 해당 작업을 처리함

									sc.preChatActivity.ibUser
											.setImageBitmap(sc.preChatActivity.bm);
									// sc.preChatActivity.ibUser.setImageResource(R.drawable.url);
									sc.preChatActivity.tvUser.setText(nickname
											+ "\r\n" + age);
								}
							});
						}
		/////			//	Thread.sleep(500);
						// for (int j = numMember; j <= 8; j++) {
						// sc.preChatActivity.ibUser2 = (ImageView)
						// sc.preChatActivity
						// .findViewById(sc.preChatActivity
						// .getResources().getIdentifier(
						// "ibUser" + j,
						// "id",
						// sc.preChatActivity
						// .getPackageName()));
						// sc.preChatActivity.tvUser2 = (TextView)
						// sc.preChatActivity
						// .findViewById(sc.preChatActivity
						// .getResources().getIdentifier(
						// "tvUser" + j,
						// "id",
						// sc.preChatActivity
						// .getPackageName()));
						//
						//
						// sc.preChatActivity.runOnUiThread(new Runnable() {
						// @Override
						// public void run() {
						// // 해당 작업을 처리함
						// sc.preChatActivity.ibUser2
						// .setImageResource(R.drawable.unknown);
						//
						//
						// sc.preChatActivity.tvUser2.setText("");
						// }
						// });
						//
						// }

					} catch (Exception ex) {
						ex.printStackTrace();
					}

				} else if ("sendGo".equals(line) && sc.preChatActivity != null) {
					sc.preChatActivity.goStart = sc.getDis().readUTF();
					if ("YES".equals(sc.preChatActivity.goStart)) {
						sc.preChatActivity.isRun = false;
					}
				} else if ("playChatting".equals(line)
						&& sc.chattingActivity != null) {
					try {
						ChatMessage chat = new ChatMessage();
						chat.setMessage(sc.getDis().readUTF());
						chat.setNickName(sc.getDis().readUTF());
						chat.setId(Long.parseLong(sc.getDis().readUTF()));

						Log.d("chatting", "getMsg : " + chat.getMessage());
						Log.d("chatting", "getNickName : " + chat.getNickName());
						Log.d("chatting", "getId : " + chat.getId());

						sc.chattingActivity.addResult(chat);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				} 
				else if ("savePartner".equals(line)
						&& sc.loveRoomActivity != null) {
					try {
						Thread.sleep(1000);
						Log.d("love","savePartner 수신");
						sc.loveRoomActivity.email=sc.getDis().readUTF();
						Log.d("love","email: " + sc.loveRoomActivity.email);
						sc.loveRoomActivity.nickname=sc.getDis().readUTF();
						Log.d("love","nickname: " + sc.loveRoomActivity.nickname);
						
						
						sc.loveRoomActivity.db.InsertDB(sc.getUserId(), sc.loveRoomActivity.email, 
								sc.loveRoomActivity.nickname);
						
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				} 
				
				else if ("playLove".equals(line)
						&& sc.loveRoomActivity != null) {
					try {
						ChatMessage chat = new ChatMessage();
						chat.setMessage(sc.getDis().readUTF());
						chat.setNickName(sc.getDis().readUTF());
						chat.setId(Long.parseLong(sc.getDis().readUTF()));

						Log.d("chatting", "getMsg : " + chat.getMessage());
						Log.d("chatting", "getNickName : " + chat.getNickName());

						sc.loveRoomActivity.addResult(chat);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}

				else if ("getPeople".equals(line)
						&& sc.arrowFormActivity != null) {
					sc.arrowFormActivity.numMale = Integer.parseInt(sc.getDis()
							.readUTF());
					sc.arrowFormActivity.numFemale = Integer.parseInt(sc
							.getDis().readUTF());
				} else if ("getUserName".equals(line)
						&& sc.arrowFormActivity != null) {

					sc.arrowFormActivity.user = sc.getDis().readUTF();
					sc.arrowFormActivity.block = false;

				} else if ("getPictures".equals(line)
						&& sc.arrowFormActivity != null) {
					int size = Integer.parseInt(sc.getDis().readUTF());
					for (int i = 0; i < size; i++) {
						long id = Long.parseLong(sc.getDis().readUTF());
						final int position = Integer.parseInt(sc.getDis().readUTF());
						URL imageURL = new URL(
								"http://zeropol2.iptime.org:8080/myproject/resources/mask_"
										+ id + ".jpg");
						HttpURLConnection conn = (HttpURLConnection) imageURL
								.openConnection();
						BufferedInputStream bis = new BufferedInputStream(
								conn.getInputStream(), 10240);
	
						sc.arrowFormActivity.bm = BitmapFactory.decodeStream(bis);
						bis.close();
						

						sc.arrowFormActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// 해당 작업을 처리함
								sc.arrowFormActivity.btUser[position-1].setBackgroundDrawable(new BitmapDrawable(sc.arrowFormActivity.bm));
								sc.arrowFormActivity.btUser[position-1].setScaleType(ScaleType.FIT_CENTER);
							}
						});

					}

					sc.arrowFormActivity.blocking = false;

				} else if ("getPartnerSelection".equals(line)
						&& sc.arrowResultView != null) {
					boolean couple = true;
					int size = Integer.parseInt(sc.getDis().readUTF());
					String sex = sc.getGender();
					int position = Integer.parseInt(sc.getDis().readUTF());
					int partner = Integer.parseInt(sc.getDis().readUTF());
					sc.arrowResultView.size = size;
					sc.arrowResultView.canvas = sc.arrowResultView.mHolder
							.lockCanvas();
					sc.arrowResultView.canvas.drawColor(Color.WHITE);
					for (int i = 0; i < size; i++) {
						Log.d("size", size + "");
						sc.arrowResultView.sex = sc.getDis().readUTF();
						Log.d("SEX", sc.arrowResultView.sex);
						sc.arrowResultView.from = Integer.parseInt(sc.getDis()
								.readUTF());
						Log.d("스레드쪽에 from", sc.arrowResultView.from + "");
						sc.arrowResultView.to = Integer.parseInt(sc.getDis()
								.readUTF());
						Log.d("스레드쪽에 to", sc.arrowResultView.to + "");
						if (sc.arrowResultView.to != 0) {
							sc.arrowResultView.drawArrows(
									sc.arrowResultView.sex,
									sc.arrowResultView.from,
									sc.arrowResultView.to);
						}
						if (!(sex.equals(sc.arrowResultView.sex))) {
							Log.d("성별확인", sc.arrowResultView.sex);
							Log.d("성별확인", sex);
							Log.d("상대방", sc.arrowResultView.from + "");
							Log.d("내 파트너", partner + "");
							Log.d("상대방의 파트너", sc.arrowResultView.to + "");
							Log.d("나", position + "");
							if (sc.arrowResultView.from == partner
									&& sc.arrowResultView.to == position) {
								Log.d("커플이", "되었다");
								couple = true;
							} else
								couple = false;
						}
					}
					sc.arrowResultView.mHolder
							.unlockCanvasAndPost(sc.arrowResultView.canvas);
					sc.arrowResultView.ready = false;
					Thread.sleep(5000);
					sc.arrowResultView.goActivity(couple);
				}

			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
